package com.amos.showdoc;

import org.junit.jupiter.api.Test;

import java.sql.*;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * ShowDocDataFix
 *
 * @author amos.wang
 * @date 2021/3/4 17:23
 */
public class ShowDocDataFix {

    @Test
    void contextLoads() throws SQLException, ClassNotFoundException {
        Class.forName("org.sqlite.JDBC");
        Connection connection = DriverManager.getConnection("jdbc:sqlite://D:\\Docker\\showdoc\\showdoc_data\\html\\Sqlite\\showdoc.db.php");
        System.out.println("Opened database successfully");
        Statement statement = connection.createStatement();

        String sql = "select page_id, page_content from page";
        ResultSet resultSet = statement.executeQuery(sql);

        Map<Integer, String> needFixDataMap = new ConcurrentHashMap<>();
        while (resultSet.next()) {
            int pageId = resultSet.getInt("page_id");
            String pageContent = resultSet.getString("page_content");
            if (pageContent == null) {
                continue;
            }

            if (pageContent.contains("http://172.16.9.55:4999/server/")) {
                pageContent = pageContent.replace("http://172.16.9.55:4999/server/", "http://172.16.6.66:4999/server/");

                needFixDataMap.put(pageId, pageContent);
            }
        }
        resultSet.close();

        // 修复数据
        needFixDataMap.forEach((pageId, pageContent) -> {
            try {
                PreparedStatement preparedStatement = connection.prepareStatement("update page set page_content = ? where page_id = ?");
                preparedStatement.setString(1, pageContent);
                preparedStatement.setInt(2, pageId);
                preparedStatement.executeUpdate();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        });

        statement.close();
        connection.close();
    }

}
